import { RouteRecordRaw } from "vue-router";
import { defineStore } from "pinia";
import { constantRoutes } from "@/router";
import { store } from "@/store";
import { listRoutes } from "@/api/menu";

const modules = import.meta.glob("../../views/**/**.vue");
const Layout = () => import("@/layout/index.vue");

/**
 * Use meta.role to determine if the current user has permission
 *
 * @param roles 用户角色集合
 * @param route 路由
 * @returns
 */
const hasPermission = (roles: string[], route: RouteRecordRaw) => {
  if (route.meta && route.meta.roles) {
    // 角色【超级管理员】拥有所有权限，忽略校验
    if (roles.includes("ROOT")) {
      return true;
    }
    return roles.some((role) => {
      if (route.meta?.roles) {
        return route.meta.roles.includes(role);
      }
    });
  }
  return false;
};

/**
 * 递归过滤有权限的异步(动态)路由
 *
 * @param routes 接口返回的异步(动态)路由
 * @param roles 用户角色集合
 * @returns 返回用户有权限的异步(动态)路由
 */
const filterAsyncRoutes = (routes: RouteRecordRaw[], roles: string[]) => {
  const asyncRoutes: RouteRecordRaw[] = [];

  routes.forEach((route) => {
    const tmpRoute = { ...route }; // ES6扩展运算符复制新对象
    if (!route.name) {
      tmpRoute.name = route.path;
    }
    // 判断用户(角色)是否有该路由的访问权限
    if (hasPermission(roles, tmpRoute)) {
      if (tmpRoute.component?.toString() == "Layout") {
        tmpRoute.component = Layout;
      } else {
        const component = modules[`../../views/${tmpRoute.component}.vue`];
        if (component) {
          tmpRoute.component = component;
        } else {
          tmpRoute.component = modules[`../../views/error-page/404.vue`];
        }
      }

      if (tmpRoute.children) {
        tmpRoute.children = filterAsyncRoutes(tmpRoute.children, roles);
      }

      asyncRoutes.push(tmpRoute);
    }
  });

  return asyncRoutes;
};

// setup
export const usePermissionStore = defineStore("permission", () => {
  // state
  const routes = ref<RouteRecordRaw[]>([]);

  // actions
  function setRoutes(newRoutes: RouteRecordRaw[]) {
    routes.value = constantRoutes.concat(newRoutes);
  }
  /**
   * 生成动态路由
   *
   * @param roles 用户角色集合
   * @returns
   */
  function generateRoutes(roles: string[]) {
    return new Promise<RouteRecordRaw[]>((resolve, reject) => {
      const asyncRoutes: RouteRecordRaw[] = [
        {
          path: "/system",
          component: "Layout",
          redirect: "/system/user",
          name: "/system",
          meta: {
            title: "系统管理",
            icon: "system",
            hidden: false,
            roles: ["GUEST", "ADMIN", "ADMIN6"],
          },
          children: [
            {
              path: "bulletinBoard",
              component: "system/bulletinBoard/index",
              name: "BulletinBoard",
              meta: {
                title: "自定义字段管理",
                icon: "dict",
                hidden: false,
                roles: ["ADMIN", "GUEST"],
                keepAlive: true,
              },
            },
            {
              path: "craftManager",
              component: "system/craftManager/index",
              name: "CraftManager",
              meta: {
                title: "工艺管理",
                icon: "cascader", //user
                hidden: false,
                roles: ["ADMIN", "GUEST"],
                keepAlive: true,
              },
            },
            {
              path: "permission",
              component: "system/permission/index",
              name: "Permission",
              meta: {
                title: "权限管理",
                icon: "role",
                hidden: false,
                roles: ["ADMIN", "ADMIN6", "GUEST"],
                keepAlive: true,
              },
            },
            {
              path: "role",
              component: "system/role/index",
              name: "Role",
              meta: {
                title: "角色组管理",
                icon: "role",
                hidden: false,
                roles: ["ADMIN", "ADMIN6", "GUEST"],
                keepAlive: true,
              },
            },
            {
              path: "company",
              component: "system/company/index",
              name: "CompanyManager",
              meta: {
                title: "企业管理",
                icon: "monitor",
                hidden: false,
                roles: ["ADMIN", "ADMIN6", "GUEST"],
                keepAlive: true,
              },
            },
            {
              path: "homePageManager",
              component: "system/homePageManager/index",
              name: "HomePageManager",
              meta: {
                title: "首页看板配置",
                icon: "monitor",
                hidden: false,
                roles: ["ADMIN", "ADMIN6", "GUEST"],
                keepAlive: true,
              },
            },
            {
              path: "orderManager",
              component: "system/orderManager/index",
              name: "OrderManager",
              meta: {
                title: "工单管理",
                icon: "Tickets",
                hidden: false,
                roles: ["ADMIN", "ADMIN6", "GUEST"],
                keepAlive: true,
              },
            },
            // {
            //   path: "user",
            //   component: "system/user/index",
            //   name: "User",
            //   meta: {
            //     title: "用户管理",
            //     icon: "user",
            //     hidden: false,
            //     roles: ["ADMIN", "GUEST"],
            //     keepAlive: true,
            //   },
            // },
            // {
            //   path: "menu",
            //   component: "system/menu/index",
            //   name: "Menu",
            //   meta: {
            //     title: "菜单管理",
            //     icon: "menu",
            //     hidden: false,
            //     roles: ["ADMIN"],
            //     keepAlive: true,
            //   },
            // },
            // {
            //   path: "dept",
            //   component: "system/dept/index",
            //   name: "Dept",
            //   meta: {
            //     title: "部门管理",
            //     icon: "tree",
            //     hidden: false,
            //     roles: ["ADMIN"],
            //     keepAlive: true,
            //   },
            // },
            // {
            //   path: "dict",
            //   component: "system/dict/index",
            //   name: "Dict",
            //   meta: {
            //     title: "字典管理",
            //     icon: "dict",
            //     hidden: false,
            //     roles: ["ADMIN"],
            //     keepAlive: true,
            //   },
            // },
          ],
        },
        // {
        //   path: "/api",
        //   component: "Layout",
        //   name: "/api",
        //   meta: {
        //     title: "接口文档",
        //     icon: "api",
        //     hidden: false,
        //     roles: ["ADMIN"],
        //     alwaysShow: true,
        //   },
        //   children: [
        //     {
        //       path: "apifox",
        //       component: "demo/api/apifox",
        //       name: "Apifox",
        //       meta: {
        //         title: "Apifox",
        //         icon: "api",
        //         hidden: false,
        //         roles: ["ADMIN"],
        //         keepAlive: true,
        //       },
        //     },
        //     {
        //       path: "swagger",
        //       component: "demo/api/swagger",
        //       name: "Swagger",
        //       meta: {
        //         title: "Swagger",
        //         icon: "api",
        //         hidden: true,
        //         roles: ["ADMIN"],
        //         keepAlive: true,
        //       },
        //     },
        //     {
        //       path: "knife4j",
        //       component: "demo/api/knife4j",
        //       name: "Knife4j",
        //       meta: {
        //         title: "Knife4j",
        //         icon: "api",
        //         hidden: true,
        //         roles: ["ADMIN"],
        //         keepAlive: true,
        //       },
        //     },
        //   ],
        // },
        // {
        //   path: "/doc",
        //   component: "Layout",
        //   name: "/doc",
        //   meta: {
        //     title: "平台文档",
        //     icon: "document",
        //     hidden: false,
        //     roles: ["ADMIN"],
        //   },
        //   children: [
        //     {
        //       path: "internal-doc",
        //       component: "demo/internal-doc",
        //       name: "InternalDoc",
        //       meta: {
        //         title: "平台文档(内嵌)",
        //         icon: "document",
        //         hidden: false,
        //         roles: ["ADMIN"],
        //       },
        //     },
        //     {
        //       path: "https://juejin.cn/post/7228990409909108793",
        //       name: "Https://juejin.cn/post/7228990409909108793",
        //       meta: {
        //         title: "平台文档(外链)",
        //         icon: "link",
        //         hidden: false,
        //         roles: ["ADMIN"],
        //       },
        //     },
        //   ],
        // },
        // {
        //   path: "/multi-level",
        //   component: "Layout",
        //   redirect: "/multi-level/multi-level1",
        //   name: "/multiLevel",
        //   meta: {
        //     title: "多级菜单",
        //     icon: "cascader",
        //     hidden: false,
        //     roles: ["ADMIN"],
        //   },
        //   children: [
        //     {
        //       path: "multi-level1",
        //       component: "demo/multi-level/level1",
        //       redirect: "/multi-level/multi-level2",
        //       name: "MultiLevel1",
        //       meta: {
        //         title: "菜单一级",
        //         icon: "",
        //         hidden: false,
        //         roles: ["ADMIN"],
        //         keepAlive: true,
        //       },
        //       children: [
        //         {
        //           path: "multi-level2",
        //           component: "demo/multi-level/children/level2",
        //           redirect: "/multi-level/multi-level2/multi-level3-1",
        //           name: "MultiLevel2",
        //           meta: {
        //             title: "菜单二级",
        //             icon: "",
        //             hidden: false,
        //             roles: ["ADMIN"],
        //             keepAlive: true,
        //           },
        //           children: [
        //             {
        //               path: "multi-level3-1",
        //               component: "demo/multi-level/children/children/level3-1",
        //               name: "MultiLevel31",
        //               meta: {
        //                 title: "菜单三级-1",
        //                 icon: "",
        //                 hidden: false,
        //                 roles: ["ADMIN"],
        //                 keepAlive: true,
        //               },
        //             },
        //             {
        //               path: "multi-level3-2",
        //               component: "demo/multi-level/children/children/level3-2",
        //               name: "MultiLevel32",
        //               meta: {
        //                 title: "菜单三级-2",
        //                 icon: "",
        //                 hidden: false,
        //                 roles: ["ADMIN"],
        //                 keepAlive: true,
        //               },
        //             },
        //           ],
        //         },
        //       ],
        //     },
        //   ],
        // },
        // {
        //   path: "/component",
        //   component: "Layout",
        //   name: "/component",
        //   meta: {
        //     title: "组件封装",
        //     icon: "menu",
        //     hidden: false,
        //     roles: ["ADMIN"],
        //   },
        //   children: [
        //     {
        //       path: "wang-editor",
        //       component: "demo/wang-editor",
        //       name: "WangEditor",
        //       meta: {
        //         title: "富文本编辑器",
        //         icon: "",
        //         hidden: false,
        //         roles: ["ADMIN"],
        //         keepAlive: true,
        //       },
        //     },
        //     {
        //       path: "upload",
        //       component: "demo/upload",
        //       name: "Upload",
        //       meta: {
        //         title: "图片上传",
        //         icon: "",
        //         hidden: false,
        //         roles: ["ADMIN"],
        //         keepAlive: true,
        //       },
        //     },
        //     {
        //       path: "icon-selector",
        //       component: "demo/icon-selector",
        //       name: "IconSelector",
        //       meta: {
        //         title: "图标选择器",
        //         icon: "",
        //         hidden: false,
        //         roles: ["ADMIN"],
        //         keepAlive: true,
        //       },
        //     },
        //     {
        //       path: "dict-demo",
        //       component: "demo/dict",
        //       name: "DictDemo",
        //       meta: {
        //         title: "字典组件",
        //         icon: "",
        //         hidden: false,
        //         roles: ["ADMIN"],
        //         keepAlive: true,
        //       },
        //     },
        //     {
        //       path: "signature",
        //       component: "demo/signature",
        //       name: "Signature",
        //       meta: {
        //         title: "签名",
        //         icon: "",
        //         hidden: false,
        //         roles: ["ADMIN"],
        //         keepAlive: true,
        //       },
        //     },
        //     {
        //       path: "table",
        //       component: "demo/table",
        //       name: "Table",
        //       meta: {
        //         title: "表格",
        //         icon: "",
        //         hidden: false,
        //         roles: ["ADMIN"],
        //         keepAlive: true,
        //       },
        //     },
        //   ],
        // },
        // {
        //   path: "/function",
        //   component: "Layout",
        //   name: "/function",
        //   meta: {
        //     title: "功能演示",
        //     icon: "menu",
        //     hidden: false,
        //     roles: ["ADMIN"],
        //   },
        //   children: [
        //     {
        //       path: "icon-demo",
        //       component: "demo/icons",
        //       name: "IconDemo",
        //       meta: {
        //         title: "Icons",
        //         icon: "el-icon-edit",
        //         hidden: false,
        //         roles: ["ADMIN"],
        //         keepAlive: true,
        //       },
        //     },
        //     {
        //       path: "/function/websocket",
        //       component: "demo/websocket",
        //       name: "/function/websocket",
        //       meta: {
        //         title: "Websocket",
        //         icon: "",
        //         hidden: false,
        //         roles: ["ADMIN"],
        //         keepAlive: true,
        //       },
        //     },
        //     {
        //       path: "other",
        //       component: "demo/other",
        //       name: "Other",
        //       meta: {
        //         title: "敬请期待...",
        //         icon: "",
        //         hidden: false,
        //         roles: ["ADMIN"],
        //       },
        //     },
        //   ],
        // },
      ];
      const accessedRoutes = filterAsyncRoutes(asyncRoutes, roles);

      setRoutes(accessedRoutes);
      console.log("accessedRoutes  ", accessedRoutes);
      console.log("accessedRoutes   ", accessedRoutes);
      resolve(accessedRoutes);
      // 接口获取所有路由
      // listRoutes()
      //   .then(({ data: asyncRoutes }) => {
      //     // 根据角色获取有访问权限的路由
      //     const accessedRoutes = filterAsyncRoutes(asyncRoutes, roles);
      //     setRoutes(accessedRoutes);
      //     resolve(accessedRoutes);
      //   })
      //   .catch((error) => {
      //     reject(error);
      //   });
    });
  }

  /**
   * 混合模式左侧菜单
   */
  const mixLeftMenu = ref<RouteRecordRaw[]>([]);
  function getMixLeftMenu(activeTop: string) {
    routes.value.forEach((item) => {
      if (item.path === activeTop) {
        mixLeftMenu.value = item.children || [];
      }
    });
  }
  return { routes, setRoutes, generateRoutes, getMixLeftMenu, mixLeftMenu };
});

// 非setup
export function usePermissionStoreHook() {
  return usePermissionStore(store);
}
